package org.dromara.bykt.service.impl;

import org.dromara.bykt.domain.BYKTCourse;
import org.dromara.bykt.domain.vo.BYKTCourseVo;
import org.dromara.bykt.mapper.BYKTCourseMapper;
import org.dromara.bykt.service.IBYKTCourseExerciseService;
import org.dromara.bykt.service.IBYKTCourseQuestionsService;
import org.dromara.bykt.service.IBYKTCourseSimulationService;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.dromara.bykt.domain.bo.BYKTCourseVideoBo;
import org.dromara.bykt.domain.vo.BYKTCourseVideoVo;
import org.dromara.bykt.domain.BYKTCourseVideo;
import org.dromara.bykt.mapper.BYKTCourseVideoMapper;
import org.dromara.bykt.service.IBYKTCourseVideoService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 课程视频Service业务层处理
 *
 * @author Hou
 * @date 2025-06-22
 */
@RequiredArgsConstructor
@Service
public class BYKTCourseVideoServiceImpl implements IBYKTCourseVideoService {

    private final BYKTCourseVideoMapper baseMapper;

    private final BYKTCourseMapper courseMapper;

    @Autowired
    private IBYKTCourseExerciseService ibyktCourseExerciseService;

    @Autowired
    private IBYKTCourseSimulationService ibyktCourseSimulationService;

    @Autowired
    private IBYKTCourseQuestionsService ibyktCourseQuestionsService;

    /**
     * 查询课程视频
     *
     * @param id 主键
     * @return 课程视频
     */
    @Override
    public BYKTCourseVideoVo queryById(Long id){
        BYKTCourseVideoVo byktCourseVideoVo = baseMapper.selectVoById(id);
        BYKTCourseVo byktCourseVo = courseMapper.selectVoOne(new LambdaQueryWrapper<BYKTCourse>().eq(BYKTCourse::getId, byktCourseVideoVo.getCourseId()));
        byktCourseVideoVo.setCategoryId(byktCourseVo.getCategoryId());
        return byktCourseVideoVo;
    }

    /**
     * 分页查询课程视频列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 课程视频分页列表
     */
    @Override
    public TableDataInfo<BYKTCourseVideoVo> queryPageList(BYKTCourseVideoBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BYKTCourseVideo> lqw = buildQueryWrapper(bo);
        Page<BYKTCourseVideoVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的课程视频列表
     *
     * @param bo 查询条件
     * @return 课程视频列表
     */
    @Override
    public List<BYKTCourseVideoVo> queryList(BYKTCourseVideoBo bo) {
        LambdaQueryWrapper<BYKTCourseVideo> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<BYKTCourseVideo> buildQueryWrapper(BYKTCourseVideoBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BYKTCourseVideo> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(BYKTCourseVideo::getId);
        lqw.eq(bo.getCourseId() != null, BYKTCourseVideo::getCourseId, bo.getCourseId());
        lqw.eq(bo.getChapterId() != null, BYKTCourseVideo::getChapterId, bo.getChapterId());
        lqw.eq(StringUtils.isNotBlank(bo.getTitle()), BYKTCourseVideo::getTitle, bo.getTitle());
        lqw.eq(StringUtils.isNotBlank(bo.getUrl()), BYKTCourseVideo::getUrl, bo.getUrl());
        lqw.eq(bo.getDuration() != null, BYKTCourseVideo::getDuration, bo.getDuration());
        lqw.eq(bo.getSort() != null, BYKTCourseVideo::getSort, bo.getSort());
        lqw.eq(StringUtils.isNotBlank(bo.getIsFree()), BYKTCourseVideo::getIsFree, bo.getIsFree());
        lqw.eq(bo.getViewCount() != null, BYKTCourseVideo::getViewCount, bo.getViewCount());
        return lqw;
    }

    /**
     * 新增课程视频
     *
     * @param bo 课程视频
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(BYKTCourseVideoBo bo) {
        BYKTCourseVideo add = MapstructUtils.convert(bo, BYKTCourseVideo.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改课程视频
     *
     * @param bo 课程视频
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(BYKTCourseVideoBo bo) {
        BYKTCourseVideo update = MapstructUtils.convert(bo, BYKTCourseVideo.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BYKTCourseVideo entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除课程视频信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
            List<Long> nonExistingIds = new ArrayList<>(ids);
            for (Long id : nonExistingIds) {
                Long aLong = ibyktCourseExerciseService.queryVideoId(id);
                if (aLong != 0) {
                    throw new ServiceException("以下视频ID被习题使用，无法删除: " + id);
                }
                Long aLong1 = ibyktCourseQuestionsService.queryVideoId(id);
                if (aLong1 != 0) {
                    throw new ServiceException("以下视频ID被刷题使用，无法删除: " + id);
                }
                Long aLong2 = ibyktCourseSimulationService.queryVideoId(id);
                if (aLong2 != 0) {
                    throw new ServiceException("以下视频ID被试卷使用，无法删除: " + id);
                }
            }
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public Long selectVideoName(String videoName) {
        BYKTCourseVideoVo byktCourseVideoVo = baseMapper.selectVoOne(new LambdaQueryWrapper<BYKTCourseVideo>().eq(BYKTCourseVideo::getTitle, videoName));
        if (byktCourseVideoVo != null) {
            return byktCourseVideoVo.getId();
        }
        return 0L;
    }

    @Override
    public Long queryChapterId(Long chapterId) {
        return baseMapper.selectCount(new LambdaQueryWrapper<BYKTCourseVideo>().eq(BYKTCourseVideo::getChapterId, chapterId));
    }

    @Override
    public Long queryCourseId(Long courseId) {
        return baseMapper.selectCount(new LambdaQueryWrapper<BYKTCourseVideo>().eq(BYKTCourseVideo::getCourseId, courseId));
    }
}
